package com.atguigu.base;

import com.atguigu.util.CastUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.io.Serializable;
import java.util.Map;

public abstract class BaseServiceImpl<T> implements BaseService<T> {

    protected abstract BaseDao<T> getEntityDao();
    @Override
    public int insert(T role) {
        return this.getEntityDao().insert(role);
    }

    @Override
    public T getById(Serializable id) {
        return this.getEntityDao().getById(id);
    }

    @Override
    public int update(T role) {
        return this.getEntityDao().update(role);
    }

    @Override
    public void delete(Serializable id) {
        this.getEntityDao().delete(id);
    }

    @Override
    public PageInfo<T> findPage(Map<String, Object> filters) {
        //1.启用分页插件
        //到底背后悄悄的做了什么事情
        // 1.1 查询满足条件的记录总数
        //SELECT count(0) FROM acl_role WHERE is_deleted = 0
        //select count(0) from ( select * from acl_role WHERE is_deleted=0 and role_name like "%"?"%" ) tmp_count
        //int pageNum = Integer.parseInt((String)filters.get("pageNum"));
        //1.2 给查询语句添加limit子句实现分页
        // select * from acl_role WHERE is_deleted=0 and role_name like "%"?"%" LIMIT ?
        int pageNum = CastUtil.castInt(filters.get("pageNum"));
        int pageSize = CastUtil.castInt(filters.get("pageSize"));
        PageHelper.startPage(pageNum,pageSize);
        //2.查询数据库获取分页查询的结果
        Page<T> page = this.getEntityDao().findPage(filters);
        //3.Page转换为PageInfo并返回
        return new PageInfo<>(page.getResult(),10);
    }
}
